package com.isorf.interceptor;

import com.isorf.util.JwtUtil;
import com.isorf.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        System.out.println("拦截的url是：" + url);
        // 从 Session 中获取用户信息进行验证
        try {
            HttpSession session = request.getSession(false); // false表示不创建新session
            if (session != null) {
                Object user = session.getAttribute("user");
                Object token = session.getAttribute("token");

                // 检查 Session 中是否有用户信息和token
                if (user != null && token != null) {
                    // 验证 token 的有效性
                    Map<String, Object> claims = JwtUtil.parseToken(token.toString());

                    // 将业务数据存储到 ThreadLocal 中
                    ThreadLocalUtil.set(claims);
                    // 放行
                    return true;
                }
            }
            // session 不存在或用户未登录
            throw new RuntimeException("用户未登录");
        } catch (Exception e) {
            // http响应状态码为401
            response.setStatus(401);
            // 不放行
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
